//
//  CaiPiaoConfirmViewController.m
//  EasyToo
//
//  Created by linshengqin on 13-8-24.
//
//

#import "CaiPiaoConfirmViewController.h"
#import "DeviceUtil.h"
#import "CaiPiaoConfirm2ViewController.h"
#import "SSQ2ViewController.h"
#define WIDTH 60
@interface CaiPiaoConfirmViewController ()

@end

@implementation CaiPiaoConfirmViewController

static CaiPiaoConfirmViewController* confirmView = nil;

+(CaiPiaoConfirmViewController*)shareConfirmView
{
    if(confirmView == nil)
    {
        confirmView = [[CaiPiaoConfirmViewController alloc]init];
    }
    return confirmView;
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]
                                          initWithTitle:@"返回"
                                          style:UIBarButtonSystemItemCancel
                                          target:self
                                          action:@selector(doClickBackAction:)];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    [self initView];    
    [self becomeFirstResponder];
	// Do any additional setup after loading the view.
}
-(void)doClickBackAction:(id)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:@""
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:@"清除号码"
                                  otherButtonTitles:@"保存号码",nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet showInView:self.view];
}
-(void)initView
{
    [self initData];
    [self initScrollView];
    [self initTableView:caipiao_model.stakeList];
    [self initButton:[caipiao_model.stakeList count]*WIDTH];
    [self initLable:[caipiao_model.stakeList count]*WIDTH];
}
-(void)initData
{
    caipiao_model = [CaiPiaoModel sharedata];
    totalPrice=0;
    for( NSNumber* price in caipiao_model.listPrice)
    {
        totalPrice += [price longValue];
        printf("price is:%ld\n",totalPrice);
    }
    totalCount = 0;
    for( NSNumber* count in caipiao_model.listNum)
    {
        totalCount += [count longValue];
        printf("totalcount is:%ld\n",totalCount);
    }
}
-(void) initScrollView
{
    _bgScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, [DeviceUtil getScreenWidth], [DeviceUtil getScreenHeight])];
    [self.view addSubview:_bgScrollView];
    _bgScrollView.contentSize = CGSizeMake(320, 1000);
    _bgScrollView.showsVerticalScrollIndicator = YES;
}
-(void) initTableView:(NSMutableArray*)namelist
{
    //由于 srollview与tableview的特性,这里用button来替代tableview;
    /*
    UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, [DeviceUtil getScreenWidth], 200) style:UITableViewStylePlain];
    [tableView setDelegate:self];
    [tableView setDataSource:self];
    [_bgScrollView addSubview:tableView];
     */
    
    for (int i  = 0; i < [namelist count]; i ++) {
        printf("count is:%d\n",[namelist count]);
        UIButton *bgBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        bgBtn.frame = CGRectMake(10, 46+i*WIDTH, 300, WIDTH);
        [bgBtn setBackgroundImage:[UIImage imageNamed:@"filmd_02"] forState:UIControlStateNormal];
        [_bgScrollView addSubview:bgBtn];
        
        UIButton *delBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        delBtn.tag = i+300;
        delBtn.frame = CGRectMake(270, 20, 20, 20);
        [delBtn addTarget:self action:@selector(delEvent:) forControlEvents:UIControlEventTouchUpInside];
        [delBtn setBackgroundImage:[UIImage imageNamed:@"cp_ssshanchu"] forState:UIControlStateNormal];
        [bgBtn addSubview:delBtn];
        
        UILabel *lottery = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 280, 30)];
        lottery.backgroundColor = [UIColor clearColor];
        if(caipiao_model.lType == 1 || caipiao_model.lType == 6)
        {
            NSString* lottery_text =[namelist objectAtIndex:i];
            NSString* temp = @"|";
            NSRange range = [lottery_text rangeOfString:temp];
            NSLog(@"found at location = %d, length = %d",range.location,[lottery_text length]);        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:lottery_text];
            [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,range.location)];
            
            [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(range.location+1,[lottery_text length]-range.location - 1)];
            
            lottery.attributedText = str;

        }
        else
        {
            lottery.textColor = [UIColor redColor];
            lottery.text = [namelist objectAtIndex:i];
        }
        lottery.font = [UIFont fontWithName:@"Arial" size:15];   //设置内容字体和字体大小
        [bgBtn addSubview:lottery];
        
        UILabel* detail = [[UILabel alloc]initWithFrame:CGRectMake(0, 30, 280, 30)];
        detail.backgroundColor = [UIColor clearColor];
        detail.textColor = [UIColor grayColor];

        NSNumber* num = [caipiao_model.listNum objectAtIndex:i];
        detail.text = [NSString stringWithFormat:@"%ld注",[num longValue]];
        detail.font = [UIFont fontWithName:@"Arial" size:13];   //设置内容字体和字体大小
        [bgBtn addSubview:detail];
    }

}
-(void)delEvent:(id)sender
{
    UIButton* btn = (UIButton*)sender;
    int i = btn.tag  - 300;
    [caipiao_model.stakeList removeObjectAtIndex:i];
    [caipiao_model.listPrice removeObjectAtIndex:i];
    [caipiao_model.listNum  removeObjectAtIndex:i];
    [_bgScrollView removeFromSuperview];
    [self initView];
}
-(void) initLable:(int)index
{
    UILabel *label_tip = [[UILabel alloc]initWithFrame:CGRectMake(0, 50+index, 100, 20)];
    label_tip.font = [UIFont fontWithName:@"Arial" size:12];   //设置内容字体和字体大小
    label_tip.text = @"我已阅读并同意";
    [_bgScrollView addSubview:label_tip];
    
    UILabel *label_tip2 = [[[UILabel alloc]initWithFrame:CGRectMake(85, 50+index, 120, 20)]autorelease];
    label_tip2.font = [UIFont fontWithName:@"Arial" size:12];   //设置内容字体和字体大小
    label_tip2.text = @"<<用户服务协议>>";
    label_tip2.textColor = [UIColor redColor];
    [_bgScrollView addSubview:label_tip2];
    
    UILabel *label_tip3 = [[[UILabel alloc]initWithFrame:CGRectMake(0, 80+index, 35, 20)]autorelease];
    label_tip3.font = [UIFont fontWithName:@"Arial" size:15];   //设置内容字体和字体大小
    label_tip3.text = @"倍投:";
    [_bgScrollView addSubview:label_tip3];
    
    
    self.times = [[[UITextField alloc] initWithFrame:CGRectMake(35, 80+index, 60, 25)]autorelease];
    [self.times setBorderStyle:UITextBorderStyleBezel];
    self.times.font =  [UIFont fontWithName:@"Arial" size:15];
    [_bgScrollView addSubview:self.times];
    self.times.delegate = self;
    self.times.keyboardType = UIKeyboardTypeDefault;
    self.times.returnKeyType = UIReturnKeyDone;
    
    if( caipiao_model.lType != 6 ) //非在大乐透
    {
        label_total = [[[UILabel alloc]initWithFrame:CGRectMake(100, 80+index, 120, 20)]autorelease];
        label_total.font = [UIFont fontWithName:@"Arial" size:15];   //设置内容字体和字体大小
        [label_total setText:[NSString stringWithFormat:@"    共%ld元",totalPrice]];
        label_total.textColor = [UIColor redColor];
        [_bgScrollView addSubview:label_total];
    }
    else
    {
        
       UILabel* label_append = [[[UILabel alloc]initWithFrame:CGRectMake(130, 80+index, 120, 20)]autorelease];
        label_append.font = [UIFont fontWithName:@"Arial" size:15];   //设置内容字体和字体大小
        label_append.text = @"追加投注";
        [_bgScrollView addSubview:label_append];
        
        UIButton* m_button = [UIButton buttonWithType:UIButtonTypeCustom];
        m_button.frame = CGRectMake(110, 80+index , 15, 15);
        [m_button setBackgroundColor:[UIColor clearColor]];
        [m_button setBackgroundImage:[UIImage imageNamed:@"RadioButton-UnSelected"] forState:UIControlStateNormal ];
        [m_button setBackgroundImage:[UIImage imageNamed:@"RadioButton-selected"]forState:UIControlStateSelected];
        m_button.selected = NO;
        [m_button addTarget:self action:@selector(lotteryAppend:) forControlEvents:UIControlEventTouchUpInside];
        [_bgScrollView addSubview:m_button];
        label_total = [[[UILabel alloc]initWithFrame:CGRectMake(240, 80+index, 100, 20)]autorelease];
        label_total.font = [UIFont fontWithName:@"Arial" size:15];   //设置内容字体和字体大小
        [label_total setText:[NSString stringWithFormat:@"   共%ld元",totalPrice]];
        label_total.textColor = [UIColor redColor];
        [_bgScrollView addSubview:label_total];
        
    }
}
-(void) initButton:(int)index
{
    //继续投注
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [backButton setFrame:CGRectMake(12, 8, 64, 28)];
    
    [backButton setTitle:@"继续投注" forState:UIControlStateNormal];        //设置button在没有选中的时候显示的字体
    
    backButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];         //设置button显示字体的大小
    
    [backButton setBackgroundImage:[UIImage imageNamed:@"jixu"] forState:UIControlStateNormal];    //设置button背景显示图片
    [backButton addTarget:self action:@selector(popView:) forControlEvents:UIControlEventTouchUpInside];
    [_bgScrollView addSubview:backButton];
    
    id_field = [[[UITextField alloc] initWithFrame:CGRectMake(10, 120+index, 300, 30)]autorelease];
    [id_field setBorderStyle:UITextBorderStyleBezel];
    id_field.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    
    id_field.placeholder = @"身份证号";
    id_field.borderStyle = UITextBorderStyleRoundedRect;
    id_field.delegate = self;
    id_field.returnKeyType = UIReturnKeyDone;
    id_field.backgroundColor = [UIColor clearColor];
    id_field.tag = 300;
//    id_field.layer.borderWidth = 1 ;
 //   id_field.layer.cornerRadius = 10 ;
    [_bgScrollView addSubview:id_field];
    
    UILabel *label_tip4 = [[[UILabel alloc]initWithFrame:CGRectMake(10, 150+index, 300, 20)]autorelease];
    label_tip4.font = [UIFont fontWithName:@"Arial" size:12];   //设置内容字体和字体大小
    label_tip4.text = @"有效的身份证号码是您彩票中奖后领奖的唯一保证";
//    label_tip4.textColor = [UIColor redColor];
    [_bgScrollView addSubview:label_tip4];
    
    UIImage *image = [UIImage imageNamed:@"select_button"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image] ;
    imageView.frame = CGRectMake(10,190+index , 10, 10);
    [_bgScrollView addSubview:imageView];
    
    UILabel *label_pay = [[[UILabel alloc]initWithFrame:CGRectMake(30, 180+index, 180, 30)]autorelease];
    label_pay.font = [UIFont fontWithName:@"Arial" size:14];   //设置内容字体和字体大小
    label_pay.text = @"选择支付方式:";
    [_bgScrollView addSubview:label_pay];
    
    UIButton *zfbButton = [[UIButton alloc] initWithFrame:CGRectMake(30, 220+index, 100, 35)];
    [zfbButton setBackgroundImage:[UIImage imageNamed:@"yinlian2"] forState:UIControlStateNormal];
    [_bgScrollView addSubview:zfbButton];
    
    /*
    UIButton *ybButton = [[UIButton alloc] initWithFrame:CGRectMake(180, 140+index, 100, 30)];
    [ybButton setBackgroundImage:[UIImage imageNamed:@"zfb"] forState:UIControlStateNormal];
    [_bgScrollView addSubview:ybButton];
     */
    
    //清空全部按钮
    UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [clearButton setFrame:CGRectMake(30, 260+index, 100, 28)];
    
    [clearButton setTitle:@"清除全部" forState:UIControlStateNormal];        //设置button在没有选中的时候显示的字体
    
    clearButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];         //设置button显示字体的大小
    [clearButton setBackgroundImage:[UIImage imageNamed:@"clear_all"] forState:UIControlStateNormal];    //设置button背景显示图片
    [clearButton addTarget:self action:@selector(clearAll:) forControlEvents:UIControlEventTouchUpInside];
    [_bgScrollView addSubview:clearButton];
    
    //下一步按钮
    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [nextButton setFrame:CGRectMake(180, 260+index, 100, 28)];
    
    [nextButton setTitle:@"下一步" forState:UIControlStateNormal];        //设置button在没有选中的时候显示的字体
    
    nextButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];         //设置button显示字体的大小
    
    [nextButton setBackgroundImage:[UIImage imageNamed:@"xyb"] forState:UIControlStateNormal];    //设置button背景显示图片
    
    [_bgScrollView addSubview:nextButton];
    
    [nextButton addTarget:self action:@selector(confirmMessge:) forControlEvents:UIControlEventTouchUpInside];


}

#pragma mark - UITextFieldDelegate

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.times resignFirstResponder];
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if( textField.tag == 300)
    {
        
        if (![self validateIdentityCard:textField.text])
        {
            UIAlertView* baseAlert = [[[UIAlertView alloc] initWithTitle:@"请输入正确的身份证号" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil] autorelease];
            [baseAlert show];

        }
        else
        {
            caipiao_model.identify = textField.text;
        }
    }
    else{
        if( ![self isPureInt:textField.text])
        {
            UIAlertView* baseAlert = [[[UIAlertView alloc] initWithTitle:@"请输入整数" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil] autorelease];
            [baseAlert show];
        }
        else
        {
            int pre_total =totalPrice / caipiao_model.times;
            
            int m_times = [textField.text intValue];
            if( m_times <= 0)
            {
                UIAlertView* baseAlert = [[[UIAlertView alloc] initWithTitle:@"请输入正整数" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil] autorelease];
                [baseAlert show];

            }
            else
            {
                caipiao_model.times = m_times;
                totalPrice = pre_total*caipiao_model.times;
                [label_total setText:[NSString stringWithFormat:@"    共%ld元",totalPrice]];
            }
            
        }
    }
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)isPureInt:(NSString*)string{
    
    NSScanner* scan = [NSScanner scannerWithString:string];
    
    int val;
    
    return[scan scanInt:&val] && [scan isAtEnd];
    
}

//身份证号
- (BOOL) validateIdentityCard: (NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)confirmMessge:(id)sender
{
    
    if ([caipiao_model.identify length] <= 0 || [id_field.text length]<=0) //身份
    {
        UIAlertView* baseAlert = [[[UIAlertView alloc] initWithTitle:@"下注失败,请先登陆或检查身份证信息" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil] autorelease];
        [baseAlert show];
        return;
    }
    caipiao_model.totalPrice = totalPrice;
    caipiao_model.totalCount = totalCount;
    CaiPiaoConfirm2ViewController  *confirmView = [[[CaiPiaoConfirm2ViewController alloc] init]autorelease];
    [self.navigationController pushViewController:confirmView animated:YES];
}

-(void)clearAll:(id)sender
{
    [caipiao_model.stakeList removeAllObjects];
    [caipiao_model.listPrice removeAllObjects];
    [caipiao_model.listNum  removeAllObjects];
    [_bgScrollView removeFromSuperview];
    [self initView];
}


- (void)onBackgroundTouch
{
    [_times resignFirstResponder];
}

-(void)popView:(id)sender
{
    [self.navigationController  popViewControllerAnimated:YES];
}
#pragma uisheetdelegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        NSLog(@"line is:%d\n",__LINE__);
        [self clearAll:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }
    else if (buttonIndex == 1)
    {
        NSLog(@"line is:%d\n",__LINE__);
        [self.navigationController popViewControllerAnimated:YES];
    }
    else if(buttonIndex == 2)
    {
        NSLog(@"line is:%d\n",__LINE__);
    }
    else if(buttonIndex == 3)
    {
        NSLog(@"line is:%d\n",__LINE__);
    }
    
}
- (void)actionSheetCancel:(UIActionSheet *)actionSheet{
    
}
-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{
    
}
-(void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex{
    
}

-(void)lotteryAppend:(id)sender
{
    UIButton *button = (UIButton *)sender;
    button.selected = !button.selected;
    if( button.selected)
    {
        caipiao_model.isAppend = YES;
        totalPrice = totalCount*caipiao_model.times*3;
        [label_total setText:[NSString stringWithFormat:@"    共%ld元",totalPrice]];
    }
    else
    {
        caipiao_model.isAppend = NO;
        totalPrice = totalCount*caipiao_model.times*2;
        [label_total setText:[NSString stringWithFormat:@"    共%ld元",totalPrice]];
    }
}
@end
